<template>
  <view>
    <block v-for="(item, index) in myVideoList" :key="index">
      <uni-card :title="item.add_date" @click="onClickCard(item)">
        <rich-text class="uni-body" :nodes="item.url_utf8" space="nbsp"></rich-text>
      </uni-card>
    </block>
    <uni-popup ref="popupPlayVideo" type="dialog" background-color="#fff">
      <view>
        <video id="myVideo" :src="state.video_src" @error="videoErrorCallback"></video>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { VideoItem } from '@/types/home'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { getMyVideoListAPI } from '@/services/home'

// 通用变量
const state = reactive({
  video_src: '',
  select_question_id: 0,
  subject_id: 1,
  applied_type: 2,
  page: 1,
  size: 10,
  total: 1,
})
const popupPlayVideo = ref<any>()
const myVideoList = ref<VideoItem[]>([])
// 点击卡片，记录播放地址
const onClickCard = (video_item: VideoItem) => {
  console.log('点击微课', video_item)
  state.video_src = video_item.url
  popupPlayVideo.value.open()
}
//处理视频播放失败
const videoErrorCallback = (e: any) => {
  uni.showModal({
    content: e.target.errMsg,
    showCancel: false,
  })
}
// 根据学科、不同申请类型获取题目列表
const getMyVideoListData = async () => {
  const data = {
    page: state.page,
    size: state.size,
  }
  const res = await getMyVideoListAPI(data)
  console.log('获取视频列表：', res)
  if (res.code == 200) {
    myVideoList.value = res.data.results
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 页面加载
onLoad(async () => {
  getMyVideoListData()
})
// 自定义触底加载更多数据
onReachBottom(async () => {
  if (myVideoList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    await Promise.all([addMoreVideoData()])
  }
})
// 添加更多可录入试题列表，且未过期，用于上拉触底新增数据
const addMoreVideoData = async () => {
  const data = {
    page: state.page + 1,
    size: state.size,
  }
  const res = await getMyVideoListAPI(data)
  console.log('获取更多试题', res)
  if (res.code == 200) {
    myVideoList.value.push(...res.data.results)
    state.page += 1
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '触底添加数据失败' })
  }
}
</script>

<style lang="scss"></style>